package cn.bb.util;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
@Component
@Aspect
public class LogUtil {
    public void log(String type,int num){
        System.out.println("日志："+currtime()+type+"手机"+num+"部");
    }
    public String currtime(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date());
    }
    /*前置通知*/
    @Before("execution( void *Phone(int))")
    public void before(JoinPoint jp){
        Object[] args = jp.getArgs();//获取目标方法的所有参数
        String methodName = jp.getSignature().getName();//获取目标方法的名称
        if("buyPhone".equals(methodName)){
            System.out.println("日志："+currtime()+"即将执行进货操作，数量为："+args[0]+"部");
        }
        if("salePhone".equals(methodName)){
            System.out.println("日志："+currtime()+"即将执行销售操作，数量为："+args[0]+"部");
        }
    }
    /*后置通知*/
    @AfterReturning("execution( void *Phone(int))")
    public void afterReturnning(JoinPoint jp){
        String methodname = jp.getSignature().getName();
        if("buyPhone".equals(methodname)){
            System.out.println("日志："+currtime()+"进货操作执行完毕");
        }
        if("salePhone".equals(methodname)){
            System.out.println("日志："+currtime()+"销售操作执行完毕");
        }
    }
    /*异常通知的配置*/
    @AfterThrowing(pointcut="execution( void *Phone(int))",throwing="e")
    public void afterThrowing(JoinPoint jp,OutOfStockException e){
        String methodname = jp.getSignature().getName();
        System.out.println(currtime()+methodname+"方法执行，发生缺货异常"+e.getMessage());
    }
    /*最终通知*/
    @After("execution( void *Phone(int))")
    public void after(JoinPoint jp){
        String methodname = jp.getSignature().getName();
        if("buyPhone".equals(methodname)){
            System.out.println(currtime()+"进货操作执行完毕，发生异常也要执行最终通知");
        }
        if("salePhone".equals(methodname)){
            System.out.println(currtime()+"销售操作执行完毕，发生异常也要执行最终通知");
        }
    }
    /*环绕通知*/
    @Around("execution( void *Phone(int))")
    public Object aroundTest(ProceedingJoinPoint pjp) throws Throwable {
        String methodname = pjp.getSignature().getName();
        long cur1 = System.currentTimeMillis();
        System.out.println(currtime()+":"+methodname+"方法开始执行，计时开始");
        try{
            return pjp.proceed();
        }finally {
            long cur2 = System.currentTimeMillis();
            System.out.println(currtime()+":"+methodname+"方法开始执行完毕，耗时："+(cur2-cur1));
        }
    }
}
